﻿/*
   Open Intel 
   Copyright © 2011 – ISC. All Rights Reserved.
*/
using System;
using Caliburn.Micro;
using ISC.RIM.Silverlight.MDNSMapService;
using OI.Framework;
using Map = ISC.MapDotNetServer.Common.Maps.Map;

namespace OI.Async
{
    public class MDNMapDefinitionQuery : IResult
    {
        readonly string MapID;

        // mdn map service proxy
        protected MapServiceClient Client
        {
            get
            {
                return _Client ?? (_Client = ServiceClients.CreateMapDefinitionServiceClient(BaselineMapStateCompleted));
            }
        }
        private MapServiceClient _Client;

        // results - a Map
        public Map MapDefintion { get; private set; }
        public string MapDefinitionString { get; private set; }


        // map id is required for querying baseline map state
        public MDNMapDefinitionQuery(string mapID)
        {
            MapID = mapID;
        }


        // execute the query here
        public virtual void Execute(ActionExecutionContext context)
        {
            Client.GetBaselineMapDescriptionStateAsync(MapID);
        }


        // async handler for getting map baseline
        void BaselineMapStateCompleted(object sender, GetBaselineMapDescriptionStateCompletedEventArgs e)
        {
            try
            {
                if (e.Error != null)
                {
                    HandleError(e.Error);
                }
                else if (string.IsNullOrEmpty(e.Result))
                {
                    throw new Exception("Empty result from GetBaselineMapDescriptionState");
                }
                else
                {
                    MapDefinitionString = e.Result;
                    MapDefintion = Map.Deserialize(MapDefinitionString);

                    if (!string.IsNullOrEmpty(MapDefintion.Error))
                    {
                        throw new Exception(MapDefintion.Error);
                    }

                }
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
            finally
            {
                Completed(this, new ResultCompletionEventArgs());
            }
        }


        // forward error to IShell
        static void HandleError(Exception ex)
        {
            IoC.Get<IShell>().HandleException(ex, "Baseline map state query error:");
        }

        public event EventHandler<ResultCompletionEventArgs> Completed;
    }
}
